﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;

namespace AutoDeployForSims.From18To10Cfg.Utility
{
    /// <summary>
    /// 这是个配置文件操作类，用来读取和设置ini配置文件
    /// </summary>
    public class ReadIni
    {
        /// <summary>
        /// 从ini配置文件中读取变量的值
        /// </summary>
        /// <param name="file">配置文件的路径</param>
        /// <param name="section">要获取的变量所在段名称</param>
        /// <param name="variable">要获取的变量名称</param>
        /// <param name="defaultValue">变量名称不存在时的默认值</param>
        /// <returns>变量的值</returns>
        public static string GetProfileString(string file, string section, string variable, string defaultValue)
        {
            string strLine, value = "";
            StreamReader sr = new StreamReader(file, Encoding.Default);
            bool isInSection = false;
            try
            {
                while ((strLine = sr.ReadLine()) != null)
                {
                    strLine = strLine.Trim();
                    //去除；注释，按；分割，截取字符串非；起始至；结束
                    string[] lineList = strLine.SplitRemoveEndEmptyEntries(new string[] { ";" });
                    if (lineList.Length > 0)
                    {
                        strLine = lineList[0];
                    }
                    else
                    {
                        continue;
                    }
                    if (Regex.IsMatch(strLine, "^\\[\\s*.*\\s*\\]"))
                    {
                        if (Regex.IsMatch(strLine, "^\\[\\s*" + section + "\\s*\\]"))
                        {
                            isInSection = true;
                        }
                        else
                        {
                            isInSection = false;
                        }
                    }
                    if (isInSection == true)
                    {
                        strLine = strLine.Trim();
                        string[] strArray = strLine.SplitRemoveEndEmptyEntries(new string[] { "=" });
                        if (strArray.Length == 1)
                        {
                            value = strArray[0].Trim();
                            if (value.Equals(variable, StringComparison.CurrentCultureIgnoreCase))
                            {
                                value = "";
                                return value;
                            }
                        }
                        else if (strArray.Length == 2)
                        {
                            value = strArray[0].Trim();
                            if (value.Equals(variable, StringComparison.CurrentCultureIgnoreCase))
                            {
                                value = strArray[1].Trim();
                                return value;
                            }
                        }
                        else if (strArray.Length > 2)
                        {
                            value = strArray[0].Trim();
                            if (value.Equals(variable, StringComparison.CurrentCultureIgnoreCase))
                            {
                                value = strLine.Substring(strLine.IndexOf("=") + 1).Trim();
                                return value;
                            }
                        }
                    }
                }
            }
            finally
            {
                sr.Close();
            }
            return defaultValue;
        }

        /// <summary>
        /// 修改ini配置文件中变量的值
        /// </summary>
        /// <param name="file">配置文件的路径</param>
        /// <param name="section">要修改的变量所在段名称</param>
        /// <param name="variable">要修改的变量名称</param>
        /// <param name="value">变量的新值</param>
        /// <returns></returns>
        public static bool SetProfileString(string file, string section, string variable, string value)
        {
            string fileContent, allLine, strLine, newLine, remarkStr;
            string getValue;
            StreamReader sr = new StreamReader(file, Encoding.Default);
            bool isInSection = false;
            fileContent = "";
            try
            {
                while ((allLine = sr.ReadLine()) != null)
                {
                    allLine = allLine.Trim();
                    if (allLine.SplitRemoveEndEmptyEntries(new string[] { ";" }).Length > 1)
                        remarkStr = ";" + allLine.SplitRemoveEndEmptyEntries(new string[] { ";" })[1];
                    else
                        remarkStr = "";
                    strLine = allLine.SplitRemoveEndEmptyEntries(new string[] { ";" })[0];
                    if (Regex.IsMatch(strLine, "^//[//s*.*//s*//]"))
                    {
                        if (Regex.IsMatch(strLine, "^//[//s*" + section + "//s*//]"))
                        {
                            isInSection = true;
                        }
                        else
                        {
                            isInSection = false;
                        }
                    }
                    if (isInSection == true)
                    {
                        strLine = strLine.Trim();
                        string[] strArray = strLine.SplitRemoveEndEmptyEntries(new string[] { "=" });
                        getValue = strArray[0].Trim();
                        if (getValue.Equals(variable, StringComparison.CurrentCultureIgnoreCase))
                        {
                            newLine = getValue + " = " + value + " " + remarkStr;
                            fileContent += newLine + "/r/n";
                            while ((allLine = sr.ReadLine()) != null)
                            {
                                fileContent += allLine + "/r/n";
                            }
                            sr.Close();
                            File.WriteAllText(file, fileContent, Encoding.Default);
                            return true;
                        }
                    }
                    fileContent += allLine + "/r/n";
                }
            }
            catch (IOException ex)
            {
                throw ex;
            }
            finally
            {
                sr.Close();
            }
            return false;
        }

        /// <summary>
        /// 按行读取ini文件，注意，由于存储大小有限不建议对大文件使用
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        public static List<string> ToStringsByRandomAccessFile(string filePath)
        {
            // 使用ArrayList来存储每行读取到的字符串
            List<string> arrayList = new List<string>();
            try
            {
                StreamReader sr = new StreamReader(filePath, Encoding.Default);
                string str;
                // 按行读取字符串
                while ((str = sr.ReadLine()) != null)
                {
                    str = str.Trim();
                    arrayList.Add(str);
                }
                sr.Close();
            }
            catch (IOException ex)
            {
                MessageBox.Show(ex.Message);
            }
            // 返回数组
            return arrayList;
        }

        /// <summary>
        /// 按行读取ini文件，读取section中的所有行
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="section">要获取的变量所在段名称</param>
        /// <param name="defaultValue">变量名称不存在时的默认值</param>
        /// <returns></returns>
        public static List<string> ReadSectionAllLine(string filePath, string section, string defaultValue)
        {
            // 使用ArrayList来存储每行读取到的字符串
            List<string> arrayList = new List<string>();
            string strLine = "";
            StreamReader sr = new StreamReader(filePath, Encoding.Default);
            //判断sectionStatusType状态，为0表示当前未找到section，1表示已找到section，2表示section已结束
            int sectionStatusType = 0;
            while ((strLine = sr.ReadLine()) != null)
            {
                strLine = strLine.Trim();
                if (Regex.IsMatch(strLine, "^\\[\\s*.*\\s*\\]"))
                {
                    if (sectionStatusType == 1)
                    {
                        sectionStatusType = 2;
                    }
                    else if (sectionStatusType == 0)
                    {
                        if (Regex.IsMatch(strLine, "^\\[\\s*" + section + "\\s*\\]"))
                        {
                            sectionStatusType = 1;
                        }
                    }
                }
                if (sectionStatusType == 0)
                {
                    continue;
                }
                else if (sectionStatusType == 1)
                {
                    strLine = strLine.Trim();
                    arrayList.Add(strLine);
                }
                else
                {
                    break;
                }

            }
            sr.Close();
            // 返回数组
            return arrayList;
        }


        public static Dictionary<string, List<string>> FastReadTDSectionAllLine(string filePath,int readChildSectionNum, string childSectionFirst, string childSectionSecond, string defaultValue)
        {
            Dictionary<string, List<string>> keyValuePairs = new Dictionary<string, List<string>>();
            //当前已经读取的子项个数
            int readChildSectionCount = 0;


            List<string> arrayList = new List<string>();
            string strLine = "";
            StreamReader sr = new StreamReader(filePath, Encoding.Default);
            //判断sectionStatusType状态，为0表示当前未找到section，1表示已找到section
            int sectionStatusType = 0;
            
            while ((strLine = sr.ReadLine()) != null && readChildSectionCount <= readChildSectionNum)
            {
                strLine = strLine.Trim();
                if (Regex.IsMatch(strLine, "^\\[\\s*.*\\s*\\]"))
                {
                    //有【】则需要判断行标志
                    if (Regex.IsMatch(strLine, "^\\[{1}" + childSectionFirst + "[0-9]+" + childSectionSecond + "\\]{1}"))
                    {
                        sectionStatusType = 1;
                        // 表示section已结束，且该行为一个新的section
                        arrayList = new List<string>();
                        keyValuePairs.Add(strLine.Trim(), arrayList);
                        readChildSectionCount++;
                    }
                    else
                    {
                        sectionStatusType = 0;
                    }
                }
                else
                {
                    //根据标志位判断是否需要加入
                    if (sectionStatusType == 1)
                    {
                        strLine = strLine.Trim();
                        arrayList.Add(strLine);
                    }
                    else
                    {
                        continue;
                    }
                }
            }
            sr.Close();

            return keyValuePairs;
        }
    }
}
